package com.util;

import javax.servlet.ServletResponse;
import java.io.PrintWriter;

public class ResponseUtil {

    public ResponseUtil() {
    }

    /**
     * 使用response输出JSON
     *
     * @Param resultMap 数据
     */
    private static void responseJson(ServletResponse response, long code, String message) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            String body = "{\"code\":" + code + ",\"msg\":" + message + "}";
            out = response.getWriter();
            out.println(body);
        } catch (Exception e) {
//            Logger.error("【JSON输出异常】" + e);
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }

    public static void faild(ServletResponse response) {
        ResponseUtil.responseJson(response, ResultCode.FAILED.getCode(), ResultCode.FAILED.getMessage());
    }

    public static void faild(ServletResponse response, String message) {
        ResponseUtil.responseJson(response, ResultCode.FAILED.getCode(), message);
    }

    public static void unauthorized(ServletResponse response) {
        ResponseUtil.responseJson(response, ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage());
    }

    public static void unauthorized(ServletResponse response, String message) {
        ResponseUtil.responseJson(response, ResultCode.UNAUTHORIZED.getCode(), message);
    }

    public static void forbidden(ServletResponse response) {
        ResponseUtil.responseJson(response, ResultCode.FORBIDDEN.getCode(), ResultCode.FORBIDDEN.getMessage());
    }

    public static void forbidden(ServletResponse response, String message) {
        ResponseUtil.responseJson(response, ResultCode.FORBIDDEN.getCode(), message);
    }
}
